mod server;
pub mod auth;

use std::sync::LazyLock;
use anyhow::{anyhow, Context};
use config::{Config, FileFormat};
use serde::Deserialize;

pub use server::ServerConfig;
pub use auth::AuthProviderConfig;

static APP_CONFIG: LazyLock<AppConfig> = LazyLock::new(|| AppConfig::load().expect("Failed to load config"));
#[derive(Debug, Deserialize)]
pub struct AppConfig{
    server: ServerConfig,
    auth: AuthProviderConfig,
}
impl AppConfig {
    pub fn server_config(&self) -> &ServerConfig {
        &self.server
    }
    pub fn auth_config(&self) -> &AuthProviderConfig {
        &self.auth
    }

    pub fn load() -> anyhow::Result<Self> {
        Config::builder()
            .add_source(
                config::File::with_name("application")
                    .required(true)
                    .format(FileFormat::Yaml)
            )
            .add_source(
                config::Environment::with_prefix("APP")
                    .try_parsing(true)
                    .separator("_")
                    .list_separator(",")
            ).build()
            .with_context(|| anyhow!("Failed to load config"))?
            .try_deserialize()
            .with_context(|| anyhow!("Failed to load config"))
    }
}

pub fn get()-> &'static AppConfig{
    &APP_CONFIG
}

